package com.lh.biz.impl;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.lh.biz.BaseBiz;
import com.lh.biz.IProductBiz;
import com.lh.biz.dto.in.product.SearchInDto;
import com.lh.biz.dto.out.product.SearchOutDto;
import com.lh.biz.dto.out.product.ShowOutDto;
import com.lh.component.search.ProductSearcher;
import com.lh.component.search.SearchQuery;
import com.lh.component.search.SearchResult;
import com.lh.component.search.index.ProductIndex;
import com.lh.dao.IProductDao;

/**
 * @author liuhui
 * @version 1.0
 * @date 2013-5-16 下午10:14:56
 */
@Service
public class ProductBizImpl extends BaseBiz implements IProductBiz {
	private static final int SEARCH_RESULT_SIZE = 12;
	@Resource
	private IProductDao productDao;
	@Resource
	private ProductSearcher productSearcher;

	@Override
	public ShowOutDto show(Long id) {
		ShowOutDto out = new ShowOutDto();
		out.setProduct(productDao.selectById(id));
		if(out.getProduct() != null ){
			SearchQuery query = new SearchQuery();
			if(out.getProduct().getCategoryid() != null ){
				query.addConditon("categoryId", out.getProduct().getCategoryid()) ;
			}
			query.addSort("salesNum", true);
			query.setBeginIndex(0);
			query.setResultSize(10);
			out.setHotList(productSearcher.search(query).getList());
		}
		return out;
	}

	@Override
	public SearchOutDto search(SearchInDto inDto) {
		SearchOutDto out = new SearchOutDto();
		SearchQuery query = new SearchQuery();
		if(StringUtils.isNotBlank(inDto.getKeywords())){
			query.setKeywords(inDto.getKeywords());
		}
		if((inDto.getMinPrice() != null && inDto.getMinPrice() > 0 )|| (inDto.getMaxPrice() != null && inDto.getMaxPrice() > 0 )){
			query.addBetween("price", inDto.getMinPrice(), inDto.getMaxPrice());
		}
		if(inDto.getCategoryId() != null ){
			query.addConditon("categoryId", inDto.getCategoryId()) ;
		}
		if(StringUtils.isNotBlank(inDto.getProperties())){
			for (String p : inDto.getProperties().split(",")) {
				query.addConditon("properties", p);
			}
		}
		if(StringUtils.isNotBlank(inDto.getSortField())){
			query.addSort(inDto.getSortField(), true);
		}
		query.setBeginIndex(inDto.getBeginIndex());
		query.setResultSize(SEARCH_RESULT_SIZE);
		query.setDefaultSearchFields("name","detail");
		query.setFacetFields("categoryId","properties");
		query.addHighlightProp("name");
		SearchResult<ProductIndex> searchResult = productSearcher.search(query);
		out.setSearchResult(searchResult);
		out.setTotal(searchResult.getTotalCount());
		return out;
	}

}
